<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="主套餐" prop="mainPlan">
        <el-input
          v-model="queryParams.mainPlan"
          placeholder="请输入主套餐"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="消费档位" prop="mainPlanLevel">
        <el-input
          v-model="queryParams.mainPlanLevel"
          placeholder="请输入消费档位"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="mainPlanStatus">
        <el-select
          v-model="queryParams.mainPlanStatus"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="停用" value="0" />
          <el-option label="在用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态变更时间" prop="mainPlanStatusTime">
        <el-date-picker
          v-model="queryParams.mainPlanStatusTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('00:00:00'), new Date('23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="号码品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入号码品牌"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="网龄(月)" prop="networkAge">
        <el-input
          v-model="queryParams.networkAge"
          placeholder="请输入网龄(月)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          type="number"
          oninput="value=value.replace(/[^0-9]/g,'')"
        />
      </el-form-item>
      <el-form-item label="入网时间" prop="joinTime">
        <el-date-picker
          v-model="queryParams.joinTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('00:00:00'), new Date('23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >

          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('00:00:00'), new Date('23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:inquire:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:inquire:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['system:inquire:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['system:inquire:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="号码" align="center" prop="phoneNumber" />
      <el-table-column label="主套餐" align="center" prop="mainPlan" />
      <el-table-column label="消费档位" align="center" prop="mainPlanLevel" />
      <el-table-column label="状态" align="center" prop="mainPlanStatus">
        <template #default="scope">
          <span>{{ formatMainPlanStatus(scope.row.mainPlanStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态变更时间"
        align="center"
        prop="mainPlanStatusTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="号码品牌" align="center" prop="brand" />
      <el-table-column label="网龄(月)" align="center" prop="networkAge" />
      <el-table-column
        label="入网时间"
        align="center"
        prop="joinTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="实名姓名" align="center" prop="realName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <span>{{ formatGender(scope.row.gender) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:inquire:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:inquire:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InquireForm ref="formRef" @success="getList" />

  <!-- 文件上传对话框 -->
  <el-dialog title="导入Excel" v-model="importDialogVisible" width="30%">
    <el-upload
      drag
      action=""
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      accept=".xlsx, .xls"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">只能上传xlsx/xls文件</div>
      </template>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InquireApi, Inquire } from '@/api/system/inquire'
import InquireForm from './InquireForm.vue'
import { watch } from 'vue'

/** 查询 列表 */
defineOptions({ name: 'Inquire' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Inquire[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  phoneNumber: undefined,
  mainPlan: undefined,
  mainPlanLevel: undefined,
  mainPlanStatus: undefined,
  mainPlanStatusTime: [],
  brand: undefined,
  networkAge: undefined,
  joinTime: [],
  realName: undefined,
  gender: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InquireApi.getInquirePage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error: any) {
    message.error(`获取数据失败：${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InquireApi.deleteInquire(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error: any) {
    message.error(`删除失败：${error.message || '未知错误'}`)
  }
}

/** 批量删除查询 */
const handleDeleteBatch = async () => {
  try {
    // 检查是否有选中项
    if (isEmpty(checkedIds.value)) {
      message.warning('请选择要删除的记录')
      return
    }

    // 删除的二次确认
    await message.delConfirm()
    await InquireApi.deleteInquireList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch (error: any) {
    message.error(`批量删除失败：${error.message || '未知错误'}`)
  }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Inquire[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InquireApi.exportInquire(queryParams)
    download.excel(data, '号码信息列表.xls')
  } catch (error: any) {
    message.error(`导出失败：${error.message || '未知错误'}`)
  } finally {
    exportLoading.value = false
  }
}

const importDialogVisible = ref(false);
const fileToUpload = ref(null);

// 监听导入对话框关闭事件，重置文件
watch(importDialogVisible, (newVal) => {
  if (!newVal) {
    fileToUpload.value = null;
  }
});

/** 导入按钮操作 */
const handleImport= () => {
  importDialogVisible.value = true;
}

/** 文件选择改变事件 */
const handleChange = (file: any) => {
  fileToUpload.value = file.raw;
}

/** 文件上传前验证 */
const beforeUpload = (file: any) => {
  if (!/\.(xlsx|xls)$/.test(file.name)) {
    message.error('只能上传xlsx/xls文件');
    return false;
  }
  return true;
}

/** 提交上传 */
const submitUpload = async () => {
  if (!fileToUpload.value) {
    message.warning('请选择要上传的文件');
    return;
  }

  const formData = new FormData();
  formData.append('file', fileToUpload.value);

  try {
    await InquireApi.importInquire(formData);
    message.success('导入成功');
    importDialogVisible.value = false;
    await getList();
  } catch (error: any) {
    message.error(`导入失败：${error.message || '请检查文件格式和内容'}`);
  }
}

/** 格式化主套餐状态 */
const formatMainPlanStatus = (status: string | number) => {
  const statusMap = {
    0: '停用',
    1: '在用'
  };
  return statusMap[status] || status;
}

/** 格式化性别 */
const formatGender = (gender: string | number) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  };
  return genderMap[gender] || gender;
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
